package com.bonc.ioc.demo.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bonc.ioc.demo.base.wrapper.McpRequestWrapper;
import com.bonc.ioc.demo.base.wrapper.McpResponseWrapper;
import com.bonc.ioc.demo.utils.AesUtil;
import com.bonc.ioc.demo.utils.Base64Util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: demo
 * @description: 参数解密过滤器
 * @author: Liyy
 * @create: 2020-08-31 19:56
 **/
public class DecryptFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换成代理类
        McpRequestWrapper mcpRequestWrapper = new McpRequestWrapper((HttpServletRequest) servletRequest);
        McpResponseWrapper mcpResponseWrapper = new McpResponseWrapper((HttpServletResponse) servletResponse);

        //如果没有参数，不做处理
        if (null == mcpRequestWrapper.getParameterMap()) {
            filterChain.doFilter(mcpRequestWrapper, servletResponse);
            return;
        }
        Map<String, String[]> parameterMap = new HashMap<>(mcpRequestWrapper.getParameterMap());
        //通过token从redis中获取到传输加密秘钥
        String aesKey = this.getAesKeyByToken("token");
        for (String key : parameterMap.keySet()) {
            System.out.println("请求的参数为：" + key);
            String[] paramValues = parameterMap.get(key);
            System.out.println("原始参数值为：" + paramValues[0]);
            //对请求参数进行稍微修改,后续可以做为加密使用
            String[] newParamValue = new String[1];
            newParamValue[0] = AesUtil.decrypt(Base64Util.decode(paramValues[0]), aesKey);
            parameterMap.put(key, newParamValue);
        }
        mcpRequestWrapper.setParameterMap(parameterMap);
        //使用复写后的wrapper
        filterChain.doFilter(mcpRequestWrapper, mcpResponseWrapper);
        //获取返回值
        byte[] content = mcpResponseWrapper.getContent();
        if (content.length > 0) {
            String originResult = new String(content, "UTF-8");
            System.out.println("返回值:" + originResult);
            JSONObject json = JSON.parseObject(originResult);
            if (null != json.get("data")) {
                //todo 对返回结果进行加密
                json.put("data", Base64Util.encode(AesUtil.encrypt(json.get("data").toString(), aesKey)));
            }
            ServletOutputStream out = servletResponse.getOutputStream();
            out.write(json.toString().getBytes());
            out.flush();
        }
    }

    @Override
    public void destroy() {

    }


    /**
     * 模拟登录
     */
    private static Map<String, String> loginInfo = new HashMap();

    static {
        loginInfo.put("token", "123456");
        loginInfo.put("123456", "CxVExRZYIhHTtJLu");
    }


    /**
     * 通过token查询AES秘钥
     *
     * @param token
     * @return
     */
    private String getAesKeyByToken(String token) {
        String userId = loginInfo.get(token);
        return loginInfo.get(userId);
    }

}
